package com.me.chat.service.impl.chat;

import com.alibaba.fastjson.JSON;
import com.me.chat.mapper.chat.ChatGroupMapper;
import com.me.chat.pojo.chat.ChatGroup;
import com.me.chat.pojo.user.UserInfo;
import com.me.chat.service.chat.ChatGroupService;
import com.me.chat.util.RedisKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @Authhor: qiu
 * @Date: 2021/12/3 12:53 下午
 */

@Service
public class ChatGroupServiceImpl implements ChatGroupService {

    @Autowired
    ChatGroupMapper chatGroupMapper;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public ChatGroup selChatGroupByGroupId(String groupId) {
        //redis 中的用户信息的key
        final String key = RedisKey.groupInfoKey(groupId);

        String groupInfoFromRedis = stringRedisTemplate.opsForValue().get(key);

        ChatGroup chatGroup = null;

        //如果redis中存在这个userInfo 直接取出缓存
        if(groupInfoFromRedis!= null && !"".equals(groupInfoFromRedis)) {
            //将值转换为对象后 直接返回出去
            chatGroup = JSON.parseObject(groupInfoFromRedis, ChatGroup.class);
            return chatGroup;
        }
        //如果redis 缓存不存在， 取数据库
        chatGroup = chatGroupMapper.selChatGroupByGroupId(groupId);
        //后续再插入reids中
        String groupJson = JSON.toJSONString(chatGroup);

        //设置一天过期时间
        stringRedisTemplate.opsForValue().set(key,groupJson,1, TimeUnit.DAYS);

        return chatGroup;
    }
}
